from rest_framework.views import APIView
from django.http import HttpResponse
import time
from rest_framework.response import Response
import json
from rest_framework import status
from rest_framework.exceptions import APIException
from django.http import Http404
from django.db.models import Q

from my_rest import permissions
from my_rest import exceptions

from api.serializers import stock_serializers
from api.serializers import user_serializers
from core.tasks import stock_tasks
from core.tasks import user_tasks

from repository import models

# Create your views here.


def test(request):
    models.OperationRecord.objects.create(count=1,operation_type_choices=1,momo='test',stock_id=1,operator_id=2)
    # print(1231)
    return HttpResponse('test')


class Test(APIView):
    # permission_classes = (permissions.IsAuthenticated,)

    def get(self, request, format=None):
        # # models.OperationRecord.objects.create(count=1, operation_type=1, momo='test', stock_id=1, operator_id=2)
        # # print(models.OperationRecord.objects.filter(id='1').first())
        # models.StockInfo.objects.filter(id=99).delete()
        #
        # condition = Q()
        # q1 = ~Q()
        # q1.connector = 'AND'
        # q2 = Q()
        # q2.connector = 'AND'
        # q1.children.append((id, 2))
        # q2.children.append(('code', 'DDDDdd409'))
        #
        # condition.add(q1, 'AND')
        # condition.add(q2, 'AND')
        print(models.StockInfo.objects.filter(~Q(id=2) & Q(code='DDDDdd409')).exists())

        return HttpResponse('test')


class Overview(APIView):
    """库存总览"""
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request, format=None):
        res = json.loads(stock_tasks.get_stock_overview())
        if res['status'] == 200 :
            serializer = stock_serializers.OverviewSerializer(res['data'], many=True)
            return Response(list(serializer.data))
        elif res['status'] == 400:
            raise exceptions.ParmError()


class OperationRecordList(APIView):
    """操作记录接口，需要带token \n
    GET: \n
        Param:
            stock_id: 仓库ID(必须)
        Return:

        Errors:
            detail: String， 系统内部错误

    POST:\n
        Args:
            operation_type: String, 操作类型(必须)
            memo: String, 备注(不必须)
            count: Int, 数量(必须)
            stock_id: Int, 对应的库存ID(必须)
        Return:
            memo: String, 备注
            count: Int, 数量,
            type: String, 操作类型
            unit: String, 计量单位
            OperatorName: String, 操作员姓名
            createdAt: Datetime, 记录时间
        Errors: 以下错误只会返回一种
            non_field_errors: List, 常规错误，取第0个值
            detail: String， 系统内部错误
    """
    permission_classes = (permissions.IsAuthenticated,)

    def get(self,request, format=None):
        stock_id = request.GET.get('stock_id')
        if not stock_id:
            raise exceptions.ParmError()
        fields = stock_serializers.OperationOrderSerializer.filter_fields
        task_res = json.loads(stock_tasks.get_operation_record(stock_id,fields))
        if task_res['status'] != 200:
            raise APIException(code=task_res['status'],detail=task_res['detail'])
        operation_records = task_res['data']
        print(operation_records)
        serializer = stock_serializers.OperationOrderSerializer(operation_records,many=True)
        return Response(list(serializer.data))

    def post(self, request, format=None):
        serializer = stock_serializers.OperationOrderSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(operator_id=request.user['id'])    # 保存操作记录时，传入当前登陆的用户id
            return Response(dict(serializer.data), status=201)

        return Response(dict(serializer.errors), status=status.HTTP_400_BAD_REQUEST)


class StockList(APIView):
    """对库存进行增、查，需要带token，只允许admin权限 \n
    GET: \n
        Return:
            status: 200
            id:
            code: String, 零件编号
            name: String, 零件名
            stock: Int, 库存数量
            threshold: Int, 警戒值
            unit: String, 计量单位

    POST: \n
        Args:
            code: String, 零件编号
            name: String, 零件名
            stock: Int, 库存数量
            threshold: Int, 警戒值
            unit: String， 计量单位
        Return:
            status: 201
            id:
            code: String, 零件编号
            name: String, 零件名
            stock: Int, 库存数量
            threshold: Int, 警戒值
            unit: String, 计量单位


    Errors: \n
        Return
            status: 400,401,,403,500
            non_field_errors: List, 常规错误，取第0个值
            detail: String， 系统内部错误以及权限错误
    """
    permission_classes = (permissions.IsAuthenticated,permissions.IsAdminOnly)

    def get(self, request, format=None):
        filter_fields = stock_serializers.StockInfoSerializer.filter_fields
        task_res = json.loads(stock_tasks.get_stock_list(*filter_fields))
        if task_res['status'] != 200:
            raise exceptions.InnerError(code=task_res['status'],detail=task_res['detail'])
        stock_list = task_res['data']
        serializer = stock_serializers.StockInfoSerializer(stock_list,many=True)
        return Response(list(serializer.data))

    def post(self, request, format=None):
        serializer = stock_serializers.StockInfoSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(operator_id=request.user['id'])    # 保存操作记录时，传入当前登陆的用户id
            return Response(dict(serializer.data), status=201)

        return Response(dict(serializer.errors), status=status.HTTP_400_BAD_REQUEST)


class StockDetail(APIView):
    """对库存进行删、改，需要带token，只允许admin权限 \n
    DELETE： \n
        Return:
            status: 204

    PUT: \n
        Args:
            code: String, 零件编号
            name: String, 零件名
            stock: Int, 库存数量
            threshold: Int, 警戒值
            unit: String， 计量单位
        Return:
            status: 201
            id:
            code: String, 零件编号
            name: String, 零件名
            stock: Int, 库存数量
            threshold: Int, 警戒值
            unit: String, 计量单位

    """
    permission_classes = (permissions.IsAuthenticated, permissions.IsAdminOnly)

    def get_object(self, pk,*fields):
        """获取原实例"""
        conditions = {'id':pk}
        task_res = json.loads(stock_tasks.get_stock_info(*fields,**conditions))
        if task_res['status'] == 200:
            return task_res['data']
        elif task_res['status'] == 404:
            raise Http404
        else:
            raise exceptions.InnerError()

    def delete(self,request, pk,format=None):
        stock_obj = self.get_object(pk)    # 判断是否有相应数据
        task_res = json.loads(stock_tasks.delete_stock(pk))
        if task_res['status'] == 200:
            return Response(status=status.HTTP_204_NO_CONTENT)
        else:
            raise exceptions.InnerError(task_res['detail'])

    def put(self,request,pk,format=None):
        stock_obj = self.get_object(pk)    # 获取原数据
        # put_data = {'id':pk}
        # put_data.update(request.data)
        # print(put_data)
        print(pk)
        serializer = stock_serializers.StockInfoSerializer(instance=stock_obj,data=request.data)

        if serializer.is_valid():
            serializer.save(operator_id=request.user['id'])
            return Response(dict(serializer.data),status=201)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class UserList(APIView):
    """对账户进行增、查，需要带token，只允许admin权限 \n
    GET: \n
        Return:
            status: 200
            id:
            code: String, 工号
            username: String, 姓名
            is_admin: Boolean, 是否是管理员
            is_active: Boolean, 是否是启用状态

    POST: \n
        Args:
            code: String, 工号
            username: String, 姓名
            password: String, 密码
            is_admin: Boolean, 是否是管理员
        Return:
            status: 201
            id:
            code: String, 工号
            username: String, 姓名
            is_admin: Boolean, 是否是管理员
            is_active: Boolean, 是否是启用状态

    Errors: \n
        Return
            status: 400,401,,403,500,501
            non_field_errors: List, 常规错误，取第0个值
            detail: String， 系统内部错误以及权限错误
    """

    permission_classes = (permissions.IsAuthenticated,permissions.IsAdminOnly)

    def get(self, request, format=None):
        filter_fields = user_serializers.UserInfoSerializer.filter_fields
        task_res = json.loads(user_tasks.get_users(*filter_fields))
        if task_res['status'] != 200:
            raise exceptions.InnerError(detail=task_res['detail'])
        user_list = task_res['data']
        serializer = user_serializers.UserInfoSerializer(user_list,many=True)
        return Response(list(serializer.data))

    def post(self, request, format=None):
        serializer = user_serializers.UserInfoSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(dict(serializer.data), status=201)

        return Response(dict(serializer.errors), status=status.HTTP_400_BAD_REQUEST)


class UserDetail(APIView):
    """对用户表进行删、改，需要带token，只允许admin权限 \n
    PUT: \n
        Args:
            code: String, 工号
            username: String, 姓名
            is_admin: Boolean, 是否是管理员
        Return:
            status: 201
            id:
            code: String, 工号
            username: String, 姓名
            is_admin: Boolean, 是否是管理员
            is_active: Boolean, 是否是启用状态

    DELETE：
        Return:
            status: 204
    """
    permission_classes = (permissions.IsAuthenticated, permissions.IsAdminOnly)

    def get_object(self, pk,*fields):
        """获取原实例"""
        conditions = {'id':pk}
        task_res = json.loads(user_tasks.get_user_info(*fields,**conditions))
        if task_res['status'] == 200:
            if task_res['data']:
                return task_res['data']
            else:
                raise Http404
        else:
            raise exceptions.InnerError(task_res['detail'])

    def delete(self,request, pk,format=None):
        user_obj = self.get_object(pk)    # 判断是否有相应数据
        task_res = json.loads(user_tasks.delete_user(pk))
        if task_res['status'] == 200:
            return Response(status=status.HTTP_204_NO_CONTENT)
        else:
            raise exceptions.InnerError(task_res['detail'])

    def put(self,request,pk,format=None):
        user_obj = self.get_object(pk)    # 获取原数据
        serializer = user_serializers.UserInfoSerializer(instance=user_obj,data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(dict(serializer.data),status=201)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class ResetPassword(APIView):
    """重置用户密码，需要带token，只允许admin权限 \n
    PUT: \n
        Args:
            password: String, 密码
        Return:
            status: 201
    """
    permission_classes = (permissions.IsAuthenticated, permissions.IsAdminOnly)

    def get_object(self, pk,*fields):
        """获取原实例"""
        conditions = {'id':pk}
        task_res = json.loads(user_tasks.get_user_info(*fields,**conditions))
        if task_res['status'] == 200:
            if task_res['data']:
                return task_res['data']
            else:
                raise Http404
        else:
            raise exceptions.InnerError(task_res['detail'])

    def put(self,request,pk,format=None):
        user_obj = self.get_object(pk)    # 获取原数据
        serializer = user_serializers.ResetPasswordSerializer(instance=user_obj,data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(status=201)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)





